<script setup lang="ts">
/**
 * @description 一个通用的图片网格组件，根据传入的 width 和 cols 计算出图片尺寸。
 * mode 为 edit 时，网格尾部显示一个按钮，点击可以从相机或相册中选择照片。
 *
 * @property mode - 在表单中使用此组件时，
 */
const props = defineProps<{
  mode: 'edit' | 'display'
  width: number
  cols: number
  videos: string[]
  thumbs: string[]
}>()

const emit = defineEmits(['pickImage', 'delete'])

const selectedVideo = ref('')
const isShowVideo = ref(false)

const pictureSize = computed(() => (props.width - 25 * (props.cols - 1)) / props.cols)

function handlePreview(index: number, videos: string[]) {
  selectedVideo.value = videos[index]
  isShowVideo.value = true
}

function handleDelete(picture: string) {
  uni.showModal({
    title: '提示',
    content: '确定要删除这条视频吗？',
    success: (result) => {
      if (result.confirm)
        emit('delete', picture)
    },
  })
}
</script>

<template>
  <view class="grid gap-25rpx" :style="{ gridTemplateColumns: `repeat(${props.cols}, minmax(0, 1fr))` }">
    <view
      v-for="thumb, index in props.thumbs"
      :key="index"
      class="relative"
      :style="{ width: `${pictureSize}rpx`, height: `${pictureSize}rpx` }"
      @tap="handlePreview(index, videos)"
    >
      <!-- 图片 Item -->
      <image
        class="rounded-10rpx"
        :style="{ width: `${pictureSize}rpx`, height: `${pictureSize}rpx` }"
        mode="aspectFill"
        object-fit="cover"
        :src="thumb"
      />
      <!-- 遮罩层 -->
      <view class="absolute top-0 left-0 right-0 bottom-0 bg-black bg-opacity-30" />
      <!-- 播放图标 -->
      <view class="absolute top-50% left-50% -translate-50%">
        <uv-icon name="play-right-fill" size="48rpx" color="#ffffff" />
      </view>
      <!-- 右上角删除按钮 -->
      <view
        v-if="props.mode === 'edit'"
        class="absolute -top-20rpx -right-20rpx flex justify-center items-center w-40rpx h-40rpx bg-#D3D3D3 rounded-32rpx"
        @tap="() => handleDelete(thumb)"
      >
        <uv-icon name="close" size="20rpx" color="#ffffff" />
      </view>
    </view>
    <!-- 上传照片按钮 -->
    <button
      v-if="mode === 'edit'"
      class="flex flex-col justify-center items-center m-0 p-0 border-1px border-solid border-#D3D3D3 rounded-10rpx bg-white"
      hover-class="tapped"
      :style="{ width: `${pictureSize}rpx`, height: `${pictureSize}rpx` }"
      @tap="$emit('pickImage')"
    >
      <image class="w-45rpx h-33rpx" src="@/static/images/video.png" />
      <Spacer height="20" />
      <view class="text-28rpx leading-28rpx text-tertiary">
        上传视频
      </view>
    </button>
  </view>
  <view v-if="isShowVideo" class="z-50 fixed top-0 left-0 bottom-0 right-0 bg-black bg-opacity-40" @tap="isShowVideo = false">
    <video :key="selectedVideo" class="absolute top-50% left-50% -translate-50%" :src="selectedVideo" @tap.stop="" />
  </view>
</template>

<style scoped>
.tapped {
  background-color: #F8F8F8;
}
</style>
